package com.zat.mes.andrmes.dofun.work

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.media.RingtoneManager
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.chad.library.adapter.base.listener.OnLoadMoreListener
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.base.BaseFragment
import com.zat.mes.andrmes.data.GetPackBean
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.data.PackBean
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.work.adapter.GetPackDialogAdapter
import com.zat.mes.andrmes.dofun.work.fragment.GetPackFragment
import com.zat.mes.andrmes.dofun.work.fragment.GetPackHasFragment
import com.zat.mes.andrmes.dofun.work.vm.GetPackModel
import com.zat.mes.andrmes.event.CheckInUnEventMessage
import com.zat.mes.andrmes.event.GetPackEventMessage
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.*
import kotlinx.android.synthetic.main.activity_bind_machine.*
import kotlinx.android.synthetic.main.activity_clock_in_read.*
import kotlinx.android.synthetic.main.activity_get_pack.*
import kotlinx.android.synthetic.main.dialog_get_pack.view.*
import kotlinx.android.synthetic.main.fragment_get_pack.*
import kotlinx.android.synthetic.main.layout_title.*
import org.greenrobot.eventbus.EventBus
import permissions.dispatcher.*
import java.util.*

/**
 * 领取裁片包
 */
@RuntimePermissions
class GetPackActivity : BaseActivity() {

    //U口读卡器,类似于外接键盘
    private var readCardUtils: ReadCardUtils? = null
    private var getPackModel: GetPackModel? = null
    private var continueScan = false
    lateinit var getFragment: GetPackFragment
    lateinit var hasFragment: GetPackHasFragment
    override fun init() {
        initView()
        initData()
    }

    private fun initView() {
        setContentView(R.layout.activity_get_pack)
        tVtitle.text = getString(R.string.title_get_pack)
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }
        llScanGetpack.setOnClickListener { showCameraWithPermissionCheck() }

    }
    /**
     * 初始化数据
     */
    private fun initData() {

        //读卡器声明
        readCardUtils = ReadCardUtils()
        initCardReader()

        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        val empId = loginResultBean.empid
        val classId = loginResultBean.classid
        val className = loginResultBean.classname
        val factoryId: Long = loginResultBean.factoryid
        val empName = loginResultBean.empname


        tvNameGetPack.text = empName
        GlideUtil.setHeader(this, loginResultBean?.img, ivHeadGetPack)
        tvCanlendarGetpack.text = DateUtil.formatDate(Date(), getString(R.string.head_date)) + DateUtil.getWeek(
            Date()
        )

        getFragment = GetPackFragment()
        hasFragment = GetPackHasFragment()

        val adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount() = 2

            override fun createFragment(position: Int): BaseFragment {
                //0 领取记录 1 未领取
                return when (position) {
                    0 -> hasFragment
                    1 -> getFragment

                    else -> hasFragment
                }
            }
        }

        vpPack.adapter = adapter
        TabLayoutMediator(
            tabPack,
            vpPack,
            object : TabLayoutMediator.TabConfigurationStrategy {
                override fun onConfigureTab(tab: TabLayout.Tab, position: Int) {
                    when (position) {
                        0 -> tab.text = getString(R.string.text_get_pack_has)
                        1 -> tab.text = getString(R.string.text_get_pack)
                    }
                }
            }).attach()



        getPackModel = ViewModelProvider(this).get(GetPackModel::class.java)

        //领取
        getPackModel?.getPackGet()?.observe(this, Observer {
            closeLoading()
            showToast(it)
            EventBus.getDefault().post(GetPackEventMessage())
            if (continueScan) {
                showCameraWithPermissionCheck()
            }
        })



        //扫码裁片包
        getPackModel?.getPackS()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            if (it == null || it.size <= 0) {
                showToast(getString(R.string.text_not_find_pack))
            } else {

                //弹框
                val dialogView = LayoutInflater.from(GetPackActivity@ this)
                    .inflate(R.layout.dialog_get_pack, null)
                val alertDialog = AlertDialog.Builder(GetPackActivity@ this)
                val showDialog = alertDialog.setView(dialogView)
                    .show()
                var packBean: PackBean? = null
                it.forEach {
                    if (it.flag) {
                        dialogView.tvProduceNameGetDialog.text = it.productName
                        dialogView.tvStyleNoGetDialog.text =
                            getString(R.string.text_style) + "：" + it.styleNO
                        dialogView.tvPackNoGetDialog.text =
                            getString(R.string.text_pack_no) + "：" + it.packNO
                        dialogView.tvColorGetDialog.text =
                            getString(R.string.text_color) + "：" + it.color
                        dialogView.tvSizeGetDialog.text =
                            getString(R.string.text_size) + "：" + it.size
                        packBean = it
                    }
                }
                if (it != null) {
                    val getPackDialogAdapter = GetPackDialogAdapter(R.layout.item_get_pack_dialog)
                    dialogView.recyclerGetpackDialog.layoutManager = LinearLayoutManager(this)
                    dialogView.recyclerGetpackDialog.adapter = getPackDialogAdapter
                    getPackDialogAdapter.setNewData(it as MutableList<PackBean>?)
                }
                dialogView.btnGetDialog.setOnClickListener {
                    showDialog.dismiss()
                    showLoading()
                    continueScan = false
                    packBean?.packId?.let { it1 ->
                        getPackModel?.loadGetPackGet(
                            it1,
                            empName,
                            empId,
                            classId,
                            className
                        )
                    }

                }
                dialogView.btnGetScanDialog.setOnClickListener {
                    showDialog.dismiss()
                    showLoading()
                    continueScan = true
                    packBean?.packId?.let { it1 ->
                        getPackModel?.loadGetPackGet(
                            it1,
                            empName,
                            empId,
                            classId,
                            className
                        )
                    }
                }
            }

        })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val qrCode = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
        if (resultCode == Activity.RESULT_OK) {
            //根据二维码查包
            showLoading()
            getPackModel?.loadPackData(qrCode)
        }
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(Intent(this, QrScanActivity::class.java), 0)
        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }

    /**
     * 初始化刷卡器
     */
    private fun initCardReader() {

        readCardUtils?.setReadSuccessListener(ReadCardUtils.OnReadSuccessListener() {
            Log.e("zhangyucode", "barcode: " + it);
            if (it.length == 8 || it.length == 10) {
                //叫唤
                val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                val r = RingtoneManager.getRingtone(applicationContext, notification)
                r.play()
//                val soundPool = SoundPool(2, AudioManager.STREAM_MUSIC, 0)
//                soundPool.load(this,R.raw.ondo,1)
//                soundPool.play(1,1f, 1f, 0, 0, 1f);
//                showLoading()
                getPackModel?.loadPackRfidData(it)
                showLoading()

            }
        });
    }

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (ReadCardUtils.isInputFromReader(this, event)) {
            if (readCardUtils != null) {
                readCardUtils?.resolveKeyEvent(event);
            }
        }
        return super.dispatchKeyEvent(event);

    }

    override fun onDestroy() {
        readCardUtils?.removeScanSuccessListener();
        readCardUtils = null;
        super.onDestroy()
    }
}
